<?php
class Album extends CActiveRecord 
{
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'album';
    }

    public function rules() {
        return array(
            array('title, description', 'required'),
            array('title', 'length', 'max' => 150),
            array('id, pid, path, title, description', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'picture' =>array(self::HAS_MANY,'Picture','album_id', 'on'=>'t.id=picture.album_id'),
        );
    }
    
    public function attributeLabels() {
        return array(
            'id'          => 'Album Category',
            'pid'         => 'Pid',
            'path'        => 'Path',
            'title'       => 'Album Title',
            'description' => 'Album Description',
        );
    }

    public function search() {

        $criteria = new CDbCriteria;
        $criteria->compare('id', $this->id);
        $criteria->compare('pid', $this->pid);
        $criteria->compare('path', $this->path, true);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('description', $this->description, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }
   
    public function getAlbumCotegory() {
        $data  = array();
        $album = Yii::app()->db->createCommand("SELECT `id`,CONCAT(`path`,'-',`id`) `abspath`,title FROM `album` ORDER BY `abspath`,`id`")->queryAll();
        if($album){
            foreach ($album as $val){
                 $data[$val['id']] = '|'.str_repeat('--',  count(explode('-', $val['abspath']))-1).$val['title'];
            }
        }
        return $data;
    }
    
    public function fixFieldPath($pid)
    {
        $one  = Yii::app()->db->createCommand("SELECT `path` FROM `albu`m WHERE `id`=:id")->bindParam(':id', $pid)->queryRow();
        return $one['path'];
    }
    public function getAlbumTree($album_id)
    {
        $pid = Yii::app()->db->createCommand("SELECT `pid`,`title` FROM `album` WHERE `id` = {$album_id}")->queryRow();
        if($pid['pid']){
            $album = Yii::app()->db->createCommand("SELECT `title` FROM `album` WHERE `id` = {$pid['pid']}")->queryRow();
            return $album['title'];
        }else{
            return $pid['title'];
        }
    }
    
}